<template>
  <div class="upload-container">
    <!-- 用于选择图片的按钮 -->
    <input
      type="file"
      ref="fileInput"
      style="display: none"
      @change="handleFileChange"
      multiple
      accept="image/*"
    />

    <!-- 图片预览区域 -->
    <div class="preview-container">
      <!-- 点击按钮触发文件选择 -->
      <div class="upload_btn link_color" @click="openFilePicker">+</div>

      <!-- 预览图像 -->
      <div
        class="image-preview"
        v-for="(image, index) in imageList"
        :key="index"
      >
        <img :src="image.url" alt="Preview" class="preview-image" />
        <span class="remove-icon" @click="removeImage(index)">x</span>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    maxSize: {
      type: Number,
      default: 5, // 默认最大上传图片数量为5
    },
  },
  data() {
    return {
      imageList: [], // 存放图片信息的数组，每个元素包含文件路径和预览图片的 URL
    }
  },
  methods: {
    openFilePicker() {
      // 打开文件选择对话框
      this.$refs.fileInput.click()
    },
    handleFileChange(event) {
      const files = event.target.files
      // 将 FileList 转换为数组
      const fileList = Array.from(files).slice(0, this.maxSize)

      // 遍历文件列表，将每个文件转换为 URL，并添加到图片预览数组中
      fileList.forEach((file) => {
        const reader = new FileReader()
        reader.onload = (e) => {
          this.imageList.push({ file: file, url: e.target.result })
        }
        reader.readAsDataURL(file)
      })

      // 清空文件输入框的值，以便允许选择相同的文件
      event.target.value = ''
    },
    removeImage(index) {
      // 移除指定索引的图片
      this.imageList.splice(index, 1)
    },
  },
}
</script>

<style>
.upload-container {
  display: inline-block; /* 将整个组件显示为内联块 */
}

.preview-container {
  display: flex; /* 使用 flex 布局 */
  align-items: center; /* 垂直居中 */
}

.upload_btn {
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  font-size: 30px;
  border: 1px solid #ccc;
}

.image-preview {
  position: relative;
  margin-left: 10px; /* 添加左边距，与按钮分隔开 */
}

.preview-image {
  width: 100px;
  height: 100px;
  object-fit: cover;
}

.remove-icon {
  position: absolute;
  top: 5px;
  right: 5px;
  cursor: pointer;
  color: white;
  background-color: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  padding: 5px;
}
</style>
